import urls from "@/config";
import rules from "@/config/rules.js";
import {
  showToast,
  showModal
} from "@/utils/util.js";
import {
  getStorageItem
} from "@/utils/storage.js";
import {
  Token
} from "@/utils/constant.js";
import store from "@/store"
let ajaxTime = 0;
const request = (params) => {
  ajaxTime++;
  let CONFIG = beforeRequest(params);
  if (CONFIG.loading) {
    uni.showLoading({
      title: "加载中...",
    });
  }
  return new Promise((resolve, reject) => {
    uni.request({
      url: `${urls.baseUrl}${CONFIG.url}`,
      method: CONFIG.method || "GET",
      data: CONFIG.data || {},
      header: CONFIG.header,
      success: (res) => {
        if (res.data.code === 0 || res.data.code === 200) {
          resolve(res.data.data);
        } else {
          afterResponse(res, CONFIG.failReq);
        }
      },
      fail: (err) => {
        reject(err);
        showToast({
          title: "网络出现错误",
          icon: "none",
        });
      },
      complete: () => {
        ajaxTime--;
        if (ajaxTime == 0) {
          setTimeout(() => {
            uni.hideLoading();
          }, 300);
        }
      },
    });
  });
};

// 请求拦截器
function beforeRequest(config) {
  let header = {};

  header["content-type"] =
    (config.data && config.data.contentType) ||
    "application/x-www-form-urlencoded";

  if (!rules.tokenWhiteList.includes(config.url)) {
    header["app-authc"] = getStorageItem(Token) || "";
  }
  if (config.data && config.data.fail) {
    config.failReq = config.data.fail;
    delete config.data.fail;
  }
  config.loading = config.loading == undefined ? true : config.loading;

  config.header = header;
  return config;
}

// 错误提示
function afterResponse(res, fail) {
  if (res.data.code === 1) {
    console.log(store);
    store.dispatch("user/logout")
    showModal({
      content: "当前账号未登录，请登陆后进行操作",
    }).then((res) => {
      if (!res) {
        fail
          ?
          fail() :
          uni.switchTab({
            url: "/pages/tabbar/tab_index/tab_index",
          });
      } else {
        uni.navigateTo({
          url: "/pages/login/login",
        });
      }
    });
  } else if (res.data.code === 60) {
    showModal({
      content: "余额不足，请充值",
    }).then((res) => {
      if (!res) {} else {
        uni.navigateTo({
          url: "/pages/gold_pay/gold_pay",
        });
      }
    });
  } else if (res.data.code === 61) {
    showModal({
      content: "已购买，无需再次购买！",
      successText: "回首页",
    }).then((res) => {
      if (!res) {} else {
        uni.switchTab({
          url: "/pages/tabbar/tab_index/tab_index",
        });
      }
    });
  } else {
    showToast({
      title: res.data.msg,
      icon: "none",
    });
  }
}

export default request;
